/**
 * @author yangjian
 */
"use strict";
jQuery(window).load(function () {

    // Page Preloader
    jQuery('#preloader').delay(100).fadeOut(function () {
        jQuery('body').delay(100).css({'overflow': 'visible'});
    });
});

//全局JS对象
var __global = {

    //JDialog 的配置参数
    jdialog: {
        timer: 2000,   //提示框的显示时间
        width: 60, //对话窗口的高度，小于100表示百分比
        height: 80, //对话框高度，小于100表示百分比
        borderWidth: 8, //边框厚度
        top: 70, //对话框距离页面顶部的距离
        messageType: {
            "000": "ok",
            "001": "error"
        },//消息类型
        effect: 1 //切换过度特效， 0， 1， 2

    },

    jformErrorMessage: {
        empty: "请填写{cname}.",
        mobile: "请输入合法的手机号码.",
        email: "请输入合法的电子邮件地址.",
        idnum: "请输入合法的身份证号码.",
        number: "请输入有效的数字."
    },

    //列表内容的配置文档
    contentList: {
        formId: 'J_List_Form',   //列表表单ID
        checkboxName: 'ids[]',   //checkbox 的name属性，用来过滤全选的checkbox
        tableId: 'J_ListTable'         //数据类表ID
    },

    resizeLayout: function () {
        if ($('#right-section').height() < ($(window).height() - 95)) {
            $('#right-section').css('min-height', $(window).height() - 95);
        }
    }

};

define(function (require, exports) {
    require("layer").config({
        path: "/res/js/framework/layer/"
    });
    require("icheck");
    require("jdialog");
    require("select2");
    require("switch");
    var template = require("jtemplate");
    require("jform");
    require("datetimepicker");
    var adjust = require('adjustform');

    require("jpreview");
    //列表页是否有选中项
    exports.hasChecked = false;

    exports.init = function () {

        __global.resizeLayout();
        $(window).resize(function () {
            __global.resizeLayout();
        });

        //菜单收开事件
        $(".nav-parent > a").on('click', function (e) {

            if ($(this).next().is(":visible")) return;

            $(".nav-parent").find(".children").slideUp("fast");
            $(this).next().slideDown("fast");
            $(".nav-parent").find(".glyphicon-minus").addClass("glyphicon-plus").removeClass('glyphicon-minus');
            $(this).find(".pull-right").addClass("glyphicon-minus").removeClass('glyphicon-plus');
            e.stopPropagation();
        });

        //初始化菜单选择项
        $(".nav-parent").each(function (idx, ele) {

            $(ele).find(".children a").each(function (idx1, item) {
                var url = $(item).attr("href");
                if (url == location.pathname) {
                    $(this).parent().addClass('active');
                    $(ele).find(".children").show();
                    return false;
                }
            });

        });


        $('.table tbody tr td span.glyphicon-picture').click(function () {

            var pic = $(this).attr('data-img');
            if (pic) {
                jpreview.load(pic);
            }
        });
        //绑定tr和checkbox的选中事件
        //$(".table-hover tbody tr").on("click", function(e) {
        //	$(this).find(".icheck").iCheck('toggle');
        //	e.stopPropagation(); //阻止冒泡
        //});

        this.initElements();

        //删除确认
        $(".item-remove").on("click", function (e) {
            e.stopPropagation();
            var url = $(this).attr("href");
            var __confirm = JDialog.win.work({
                title: "删除",
                width: 340,
                height: 180,
                borderWidth: 8,
                lock: true,
                effect: 0,
                content: '<div style="padding-top: 15px;">确定要删除该条记录吗？</div>',
                icon: 'warn',
                button: {
                    '确认': function () {
                        $.get(url, function (data) {
                            __confirm.close();
                            if (data.code == "000") {
                                JDialog.tip.work({type: "ok", content: data.message, timer: 1000});
                                setTimeout(function () {
                                    location.reload();
                                }, 1000)
                            } else {
                                JDialog.tip.work({type: "error", content: data.message, timer: __global.jdialog.timer});
                            }
                        }, "json");
                    },
                    '取消': function () {
                        __confirm.close();
                    }
                }
            });
            return false;
        });

        //屏蔽当前active tab点击事件
        $(".nav-tabs .active a").click(function () {
            return false;
        });


        $('.js-deletes').click(function (e) {

        });
    //点击自定义菜单
        $("#defined").click(function(){
            require('jdialog');
            var content = template('defined_table');
            var configs ={
                title:"配置列表项",
                content: content,
                width:350,
                height:600,
                button:{
                    '保存':function () {
                        if (!exports.formCheckHandler('defined_edit')) {
                            return;
                        }
                        var checklength=$("#defined_edit").find("input[type='checkbox']:checked").length;
                        if(checklength<=0) {
                            layer.alert("至少保留一项")
                            return false;
                        }
                        var formData = $('#defined_edit').serialize();


                        var url = '/admin/common/setCustomForm';
                        $.post(url, formData, function (data) {
                            if (data.code == '000') {
                                JDialog.tip.work({
                                    type: "ok",
                                    content: '操作成功',
                                    lock: true,
                                    timer: __global.jdialog.timer
                                });
                                exports.dlg.close();
                                location.reload();

                            }
                            else {
                                JDialog.tip.work({
                                    type: "error",
                                    content: data.message,
                                    lock: true,
                                    timer: __global.jdialog.timer
                                });
                            }

                        }, 'json');
                    },
                    '关闭':function () {
                        exports.dlg.close();
                        exports.dlg = null;
                        location.reload();
                    }
                }
            }
            exports.dlg = JDialog.win.work($.extend(__global.jdialog, configs));
            require('nestable');
            $('#nestable3').nestable({maxDepth:1});
        })




        //点击个人信息
        //占击修改个人信息
        $('#js_global_modify_info').click(function () {
            require('jdialog');

            var content = template('global_editinfo');
            var configs = {
                title: '修改帐户',
                content: content,
                button: {
                    '保存': function () {
                        if (!exports.formCheckHandler('global_editinfo_form')) {
                            return;
                        }
                        var formData = $('#global_editinfo_form').serialize();
                        var url = '/admin/manager/editSelfInfo';
                        $.post(url, formData, function (data) {
                            if (data.code == '000') {
                                JDialog.tip.work({
                                    type: "ok",
                                    content: '操作成功',
                                    lock: true,
                                    timer: __global.jdialog.timer
                                });
                                exports.dlg.close();
                                location.reload();

                            }
                            else {
                                JDialog.tip.work({
                                    type: "error",
                                    content: data.message,
                                    lock: true,
                                    timer: __global.jdialog.timer
                                });
                            }

                        }, 'json');

                    },
                }
            };

            exports.dlg = JDialog.win.work($.extend(__global.jdialog, configs));
            $('#extend_modify_password').click(function () {

                if ($(this).val() == '修改密码') {
                    var org = $('<div class="form-group modify_new_field"><label class="col-sm-2 control-label" ><span class="asterisk">*</span>原密码</label><div class="col-sm-8"><input type="password" dtype="password" required class="form-control" maxlength="32" name="data[orgpwd]" value="" placeholder="原密码"/><p class="help-block"></p></div></div>');
                    $(this).closest(".form-group").before(org);
                    var newpassword = $('<div class="form-group modify_new_field"><label class="col-sm-2 control-label" ><span class="asterisk">*</span>新密码</label><div class="col-sm-8"><input type="password" dtype="password" required class="form-control" maxlength="32" name="data[password]" value="" placeholder="新密码"/><p class="help-block"></p></div></div>');

                    $(this).closest(".form-group").before(newpassword);
                    var confirmpwd = $('<div class="form-group modify_new_field"><label class="col-sm-2 control-label" ><span class="asterisk">*</span>确认密码</label><div class="col-sm-8"><input type="password" dtype="password" required class="form-control" maxlength="32" name="data[confirm]" value="" placeholder="确认密码"/><p class="help-block"></p></div></div>');

                    $(this).closest(".form-group").before(confirmpwd);
                    $(this).val('取消修改密码');

                }
                else {
                    $(this).closest('form').find('.modify_new_field').remove();
                    $(this).val('修改密码');

                }

            });


        });

        $('#js_global_my_info').click(function () {
            require('jtemplate');
            require('jdialog');

            var content = template('global_myinfo');
            var configs = {
                title: '个人资料',
                width: 600,
                content: content,
                button: {
                    '关闭': function () {
                        exports.dlg.close();
                        exports.dlg = null;
                    }
                }
            };

            exports.dlg = JDialog.win.work($.extend(__global.jdialog, configs));

        });
        $(".inner-container [data-act='operateAll']").on("click","a",function(){
            var actionName = $(this).data("action");
            switch(actionName){
                case 'delete':exports.list_bacth_delete();break;
                case 'on':exports.list_bacth_on();break;
                case 'off':exports.list_bacth_off();break;
            }
        });
    }

    exports.initElements = function () {
        adjust.adjust();
        //初始化list table collspan
        $("#J_ListTable .no-records").each(function () {

            var th = $(this).parent().parent().prev().children(":first").children();
            $(this).attr('colspan', th.length);

        });

        //switch
        $(".bswitch").bootstrapSwitch({
            onColor: 'success',
            offColor: 'danger'
        });

        //icheck初始化
        $(".icheck").iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass: 'iradio_minimal-blue',
            increaseArea: '20%' // optional
        });
        //icheck全选事件
        $(".check-all").on("ifChecked", function () {
            $(this).parents("table").find('[name="' + __global.contentList.checkboxName + '"]').iCheck('check');
        }).on("ifUnchecked", function () {
            $(this).parents("table").find('[name="' + __global.contentList.checkboxName + '"]').iCheck('uncheck');
        });
        var listcheckboxes = $('table#J_ListTable').find('[name="' + __global.contentList.checkboxName + '"]');
        //console.log(listcheckboxes);
        listcheckboxes.on('ifChanged', function () {
            var unchecked = 0;
            for (var i = 0; i < listcheckboxes.length; i++) {
                //console.log($(listcheckboxes[i]).prop('checked'));
                if ($(listcheckboxes[i]).prop('checked')) {
                    exports.hasChecked = true;
                }
                else {
                    unchecked++;
                }
            }
            if (unchecked == listcheckboxes.length) {
                exports.hasChecked = false;
                $(".inner-container > .button-group > .input-sm").prop('disabled', 'disabled');
                $(".inner-container [data-act='operateAll']").find("button").prop("disabled",true);

            }
            else {
                $(".inner-container > .button-group > .input-sm").removeProp('disabled');
                $(".inner-container [data-act='operateAll']").find("button").prop("disabled",false);
            }
        });
        if (!exports.hasChecked) {
            $(".inner-container > .button-group > .btn").prop('disabled', 'disabled');
            $(".inner-container [data-act='operateAll']").find("button").prop("disabled",true);
        }
        //新版替换icheck控件
        $(".check-all").on("change",function(){
            if($(this).is(":checked")){
                $(this).parents("table").find('[name="' + __global.contentList.checkboxName + '"]').prop("checked",true);
            }else {
                $(this).parents("table").find('[name="' + __global.contentList.checkboxName + '"]').prop("checked",false);

            }
        });
        var check_item = $('table#J_ListTable').find('[name="' + __global.contentList.checkboxName + '"]');
        check_item.on("change",function(){
            var unchecked = 0;
            for (var i = 0; i < check_item.length; i++) {
                //console.log($(listcheckboxes[i]).prop('checked'));
                if ($(check_item[i]).prop('checked')) {
                    exports.hasChecked = true;
                }
                else {
                    unchecked++;
                }
            }
            if (unchecked == check_item.length) {
                exports.hasChecked = false;
                $(".inner-container > .button-group > .input-sm").prop('disabled', 'disabled');
                $(".inner-container [data-act='operateAll']").find("button").prop("disabled",true);

            }
            else {
                $(".inner-container > .button-group > .input-sm").removeProp('disabled');
                $(".inner-container [data-act='operateAll']").find("button").prop("disabled",false);
            }
            if(unchecked==0) {
                $(".check-all").prop("checked",true);
            }else {
                $(".check-all").prop("checked",false);
            }
        });

        //select2
        $('.select2').select2({});

        //每页显示多少条组件
        /*
         var pagesize = $(".search-form input[name=pagesize]").val();
         if(!pagesize){
         pagesize = 15;
         }
         console.log(pagesize);
         var avail = [5,10,15,20,30,50];
         var sElem = $("<select id='pagesize'></select>");
         for(var i = 0;i < avail.length;i ++){
         if(avail[i] == pagesize){
         sElem.append($("<option selected='selected' value='"+avail[i]+"'>每页显示"+avail[i]+"条记录</option>"));
         }
         else{

         sElem.append($("<option value='"+avail[i]+"'>每页显示"+avail[i]+"条记录</option>"));
         }
         }
         sElem.change(function(){
         $(".search-form input[name=pagesize]").val($(this).find(":selected").val());
         $(".search-form").submit();

         });
         $("#J_ListTable").closest('form').after(sElem);*/
        //分页组件更改pagesize
        $('#per-pagesize').on('change', function () {
            var pagesize = $(this).val();
            var url = location.href;
            if (url.indexOf('pagesize=') == -1) {
                if (url.indexOf('?') == -1) {
                    url += '?pagesize=' + pagesize;
                } else {
                    url += '&pagesize=' + pagesize;
                }
            } else {

                url = url.replace(/pagesize=(\d+)/gmi, 'pagesize=' + pagesize);
            }

            //alert(url);
            location.replace(url);
        });
        //新版分页组件更改pagesize
        var changePageSize = function(val) {
            var pagesize = val;
            var url = location.href;
            if (url.indexOf('pagesize=') == -1) {
                if (url.indexOf('?') == -1) {
                    url += '?pagesize=' + pagesize;
                } else {
                    url += '&pagesize=' + pagesize;
                }
            } else {

                url = url.replace(/pagesize=(\d+)/gmi, 'pagesize=' + pagesize);
            }
            location.replace(url);
        };
        $("#pageSize").on("click","li",function(){
            changePageSize($(this).data("value"));
        });
        //初始化日历控件
        $.fn.datetimepicker.dates['zh-CN'] = {
            days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
            daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
            daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
            months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            today: "今天",
            suffix: [],
            meridiem: ["上午", "下午"]
        };
        $('.mdate').datetimepicker({
            language: "zh-CN",  //语言包
            format: "yyyy-mm-dd", //日期格式
            minView: "month", //最小视图，默认精确到小时
            autoclose: true,
            todayBtn: true,
            pickerPosition: "bottom-left"
        });

    }

    //通用表单验证处理
    exports.formCheckHandler = function (form_id, _lock) {
        var __form = new JForm({
            formId: form_id,
            continueCheck: true,
            filter: function (ele) {  //需要验证的表单元素过滤

                return (($(ele).attr('required') == undefined && $(ele).val()=="") || $(ele).prop("disabled"));
            },
            showMessage: function (type, message, ele) { //错误处理接口

                var errorElements = $(ele).parents(".form-group").next();
                if (!errorElements.hasClass('help-block')) {
                    errorElements = $(ele).parents(".form-group").find(".help-block");
                }
                if (type == "error") {
                    errorElements.addClass("text-error").html(message);
                    ele.focus();
                } else {
                    errorElements.removeClass("text-error").empty();
                }
            }
        });

        //设置报错提示信心
        __form.setMessage(__global.jformErrorMessage);

        return __form.checkFormData();
    }

    /**
     * 通用回调处理
     * @param data 服务器返回数据，对象
     * @param successCallback 操作成功时回调函数
     * @param failCallback 操作失败时回调函数
     */
    exports.ajaxCallback = function (data, successCallback, failCallback) {
        if (data.code == "000") {
            JDialog.tip.work({type: "ok", content: data.message, lock: true, timer: __global.jdialog.timer});
            if (typeof successCallback == 'function') {
                successCallback();
            }
        } else {
            JDialog.tip.work({type: "error", content: data.message, timer: __global.jdialog.timer});
            if (typeof failCallback == 'function') {
                failCallback();
            }
        }
    }
    /**
     * 用bizRetVo返回时调用
     * @param option
     */
    exports.ajaxResult = function (url, data, callback, failback) {
        layer.load();
        $.ajax({
            type: 'POST',
            url: url,
            data: data,
            dataType: 'json',
            success: function (thisData) {
                layer.closeAll("loading");
                if (thisData.code == '001') {
                    layer.alert(thisData.message, {
                        icon: 2, timeout: 1500, end: function () {
                            if ($.isFunction(failback)) {
                                failback(thisData);
                            } else {

                            }
                        }
                    });
                } else {
                    if ($.isFunction(callback)) {
                        callback(thisData);
                    } else {
                        layer.msg(thisData.message, {
                            icon: 1, timeout: 1500, end: function () {
                                var operation = exports.currentOpt.split('/');
                                ;
                                if (operation[2] == 'add') {
                                    location.href = '/' + operation[0] + '/' + operation[1] + '/index.shtml';
                                    return;
                                }
                                location.reload(true);
                            }
                        });
                    }
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                layer.closeAll("loading");
                layer.alert("系统出了小差，请联系管理员！", {icon: 2});
            }
        });
    }
    /**
     * 表单提交通用处理函数
     * @param formId
     * @param url
     * @param successCallback
     * @param failCallback
     * @returns {boolean}
     */
    exports.formSubmit = function (formId, url, successCallback, failCallback) {

        if (!exports.formCheckHandler(formId)) return false;
        //collect form data
        var formData = $('#' + formId).serialize();
        $.post(url, formData, function (result) {
            exports.ajaxCallback(result, successCallback, failCallback);
        }, 'json');
    }

    //检测是否已存在
    exports.checkExists = function (configs) {
        $(".check-exists").on('blur', function () {
            var value = $(this).val().trim();
            if (value == '') return false;
            var txt = $(this).attr('placeholder');
            var field = $(this).data('field');
            var that = this;
            $.post(configs.check_url, {
                field: field,
                value: value
            }, function (data) {
                var errorElements = $(that).parents(".form-group").next();
                if (data.code == '000') {
                    that.focus();
                    errorElements.addClass("text-error").html(txt + '已存在');
                } else {
                    errorElements.removeClass("text-error").empty();
                }
            }, 'json');
        });
    }

    //列表页面的bootswitch初始化
    exports.bswitctListInit = function (configs) {

        $('.bswitch-list').on("switchChange.bootstrapSwitch", function (event, state) {
            var id = $(this).data('id');
            var field = $(this).data('field');
            var value = state == false ? 0 : 1;
            $.post(configs.set_url, {
                id: id,
                field: field,
                value: value
            }, function (data) {
                if (data.code == '000') {
                    JDialog.tip.work({type: "ok", content: data.message, lock: false, timer: __global.jdialog.timer});
                } else {
                    JDialog.tip.work({
                        type: "error",
                        content: data.message,
                        lock: false,
                        timer: __global.jdialog.timer
                    });
                }
            }, 'json');
        });

        //新版switch
        if($(".css-switch").length>0){
            $(".css-switch input").on("change",function(){
                var id = $(this).data('id');
                var field = $(this).data('field');
                var value = $(this).is(":checked") ? 1 : 0;
                $.post(configs.set_url, {
                    id: id,
                    field: field,
                    value: value
                }, function (data) {
                    if (data.code == '000') {
                        JDialog.tip.work({type: "ok", content: data.message, lock: false, timer: __global.jdialog.timer});
                    } else {
                        JDialog.tip.work({
                            type: "error",
                            content: data.message,
                            lock: false,
                            timer: __global.jdialog.timer
                        });
                    }
                }, 'json');
            });
        }
    };

    //添加页面的bootswitch初始化
    exports.bswitchAddInit = function () {
        $('.bswitch-add').on("switchChange.bootstrapSwitch", function (event, state) {
            var value = state == false ? 0 : 1;
            $(this).parents('.bootstrap-switch-wrapper').next().val(value);
        });
    }

    exports.url = function (path) {
        return path;
    }
    //一般用于注册登录返回错误信息
    exports.error=function(msg,callback){
        if(exports.loadingIndex){
            layer.close(exports.loadingIndex);
        }
        layer.alert('<div class="c-danger tc">'+msg+'</div>',{title:"温馨提示",end:function(){
            if(!!callback) {
                callback();
            }
        }});
    };

//url,data,callback
    exports.ajaxHandle = function (options) {
        var defaults = {
            type: "post",
            url: '',
            data: null,
            dataType: "json",
            async: true,
            $btn: null,
            closeLoading: true,//嵌套调用ajax，外层ajax要设为false，否则里层外层ajax的always会关闭里层beforesend的loding
            isLoading: true,
            callback: null,      //成功返回回调入口
            errorback: null  //错误返回回调入口
        };
        var opts = $.extend(defaults, options);
        var url = opts.url;
        url += url.indexOf("?") == -1 ? "?" : "&";
        url += "t=" + new Date().getTime();
        var request = $.ajax({
            type: opts.type,
            url: url,
            data: opts.data,
            async: opts.async,
            dataType: opts.dataType,
            closeLoading: opts.closeLoading,
            beforeSend: function () {

                if (opts.isLoading) {
                    exports.loadingIndex = layer.load(16, {shade: [0.1, '#fff']});
                }
                if (opts.$btn) {
                    opts.$btn.prop("disabled", true);
                }
            }
        }).fail(function (jqXHR, textStatus, errorThrown) {

            if (exports.loadingIndex) {
                layer.close(exports.loadingIndex);
            }
            //layer.alert('<div class="red" style="margin-left:50px;"><p>textStatus：'+textStatus+'</p><p>status：'+jqXHR.status+'</p><p>readyState：'+jqXHR.readyState+'</p></div>',{title:"请求出错信息"});

            layer.alert('<div class="red" style="margin-left:50px;">系统超时，请稍后重试！</div>', {title: "请求出错信息"});

            if (opts.$btn) {
                opts.$btn.prop("disabled", false);
            }
        }).done(function (data) {
            if (data.code === "000") {
                if (typeof opts.callback == "function") {
                    opts.callback(data);
                } else {
                    layer.msg('<div class="msg_success">' + data.message + '</div>', {
                        shade: 0.1,
                        skin: "layui-layer-hui"
                    }, function () {
                        window.location.reload(true);
                    });
                }
            } else {
                if (opts.$btn) {
                    opts.$btn.prop("disabled", false);
                }
                if (typeof opts.errorback == "function") {
                    opts.errorback(data);
                } else {
                    layer.alert('<p class="tc c-danger">' + data.message + '</p>', {title: "温馨提示"});
                }

                if (!opts.closeLoading) {
                    //嵌套ajax的请求失败，就需要关闭loading
                    layer.close(exports.loadingIndex);
                }
            }
        }).always(function () {
            if (exports.loadingIndex && opts.closeLoading) {
                layer.close(exports.loadingIndex);
            }
            /*if(opts.$btn) {
             opts.$btn.prop("disabled", false);
             }*/
        });
        return request;
    };
    //批量启用
    exports.list_bacth_on=function(){
        var urlpathinfo = document.location.pathname.split('/');
        var url = '/' + urlpathinfo[1] + '/' + urlpathinfo[2] + '/do_updateStatus?type=1';
        var __confirm = JDialog.win.work({
            title: "启用",
            width: 340,
            height: 180,
            borderWidth: 8,
            lock: true,
            effect: 0,
            content: '<div style="padding-top: 15px;">确定要批量启用这些记录吗？</div>',
            icon: 'warn',
            button: {
                '确认': function () {
                    $.post(url, $("#J_List_Form").serialize(), function (data) {
                        __confirm.close();
                        if (data.code == "000") {
                            JDialog.tip.work({type: "ok", content: data.message, timer: 1000});
                            setTimeout(function () {
                                location.reload();
                            }, 1000)
                        } else {
                            JDialog.tip.work({type: "error", content: data.message, timer: __global.jdialog.timer});
                        }
                    }, "json");
                },
                '取消': function () {
                    __confirm.close();
                }
            }

        });


    };
    //批量禁用
    exports.list_bacth_off=function(){

        var urlpathinfo = document.location.pathname.split('/');
        var url = '/' + urlpathinfo[1] + '/' + urlpathinfo[2] + '/do_updateStatus?type=0';
        var __confirm = JDialog.win.work({
            title: "禁用",
            width: 340,
            height: 180,
            borderWidth: 8,
            lock: true,
            effect: 0,
            content: '<div style="padding-top: 15px;">确定要批量禁用这些记录吗？</div>',
            icon: 'warn',
            button: {
                '确认': function () {
                    $.post(url, $("#J_List_Form").serialize(), function (data) {
                        __confirm.close();
                        if (data.code == "000") {
                            JDialog.tip.work({type: "ok", content: data.message, timer: 1000});
                            setTimeout(function () {
                                location.reload();
                            }, 1000)
                        } else {
                            JDialog.tip.work({type: "error", content: data.message, timer: __global.jdialog.timer});
                        }
                    }, "json");
                },
                '取消': function () {
                    __confirm.close();
                }
            }

        });

    };
    //批量删除
    exports.list_bacth_delete =function (){

        var urlpathinfo = document.location.pathname.split('/');
        var url = '/' + urlpathinfo[1] + '/' + urlpathinfo[2] + '/deletes';
        var __confirm = JDialog.win.work({
            title: "删除",
            width: 340,
            height: 180,
            borderWidth: 8,
            lock: true,
            effect: 0,
            content: '<div style="padding-top: 15px;">确定要批量删除这些记录吗？</div>',
            icon: 'warn',
            button: {
                '确认': function () {
                    //alert($("#J_List_Form").serialize());
                    $.post(url, $("#J_List_Form").serialize(), function (data) {
                        __confirm.close();
                        if (data.code == "000") {
                            JDialog.tip.work({type: "ok", content: data.message, timer: 1000});
                            setTimeout(function () {
                                location.reload();
                            }, 1000)
                        } else {
                            JDialog.tip.work({type: "error", content: data.message, timer: __global.jdialog.timer});
                        }
                    }, "json");
                },
                '取消': function () {
                    __confirm.close();
                }
            }

        });
    }


    /**
     * 输入后回车触发
     * @param {$} $input 输入框对象
     * @param {function} callback 回调
     * */
    exports.inputEnterCallback=function($input,callback){
        $input.keyup(function(e){
            if(!e) e = window.event;
            if((e.keyCode || e.which) == 13){
                callback(e);
                return false;
            }
        });
    };
    /**
     * 金额格式化
     * @param {int} s 金额
     * @param {Int} [n=2] 取小数位数(默认为取2位小数)
     * @return {string} 返回格式后的金额
     * */
    exports.formatMoney=function(s,n){
        n = n > 0 && n <= 20 ? n : 2;
        s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
        var l = s.split(".")[0].split("").reverse(),
            r = s.split(".")[1];
        var t = "";
        for(var i = 0; i < l.length; i ++ )
        {
            t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
        }
        return t.split("").reverse().join("") + "." + r;
    };

    /**
     * 字数输入检查
     * @param $input 输入框对象
     * @param options 参数配置
     * @returns {boolean}
     */
    exports.checkNumFormatInput=function ($input,options){
        layer.config({
            tipsMore:false
        });
        var defaults = {
            type:0,             //类型(小数位数，0为正整数)
            emptyTipStr:null,   //空值提示语
            tipStr:null,        //提示语
            max: null,          //最大值
            maxTipStr:null,     //超过最大值提示语
            min:null,           //最小值
            tipMinStr:null      //少于最小值提示语
        };
        var opts = $.extend(defaults, options);
        var num=$input.val();
        if(num=="" || num==0){
            var emptyTipStr=opts.emptyTipStr || "请输入大于0的数值";
            layer.tips(emptyTipStr, $input);
            return false;
        }
        if(opts.type==0){
            if (!/^\+?[1-9]\d*$/.test(num)) {
                var tipStr = opts.tipStr || "请输入正整数";
                layer.tips(tipStr, $input);
                return false;
            }
        }else if(opts.type==1){
            if (!/^([1-9]\d*|[0])(.\d{1})?$/.test(num)){
                var tipStr = opts.tipStr || "请输入1位小数正数或正整数";
                layer.tips(tipStr,$input);
                return false;
            }
        }else if(opts.type==2){
            if (!/^([1-9]\d*|[0])(.\d{1,2})?$/.test(num)){
                var tipStr = opts.tipStr || "请输入两位小数正数或正整数";
                layer.tips(tipStr,$input);
                return false;
            }
        }else{
            if (!/^([1-9]\d*|[0])(.\d{1,3})?$/.test(num)){
                var tipStr = opts.tipStr || "请输入三位小数正数或正整数";
                layer.tips(tipStr,$input);
                return false;
            }
        }

        //不能大于某个数
        if(opts.max!=null){
            var f_max = parseFloat(opts.max);
            var f_num = parseFloat(num);
            var result = f_num-f_max;
            if(result > 0){
                var maxTipStr = opts.maxTipStr || "您输入的数字不能大于"+f_max+"!";
                layer.tips(maxTipStr,$input);
                return false;
            }
        }
        //不能小于某个数
        if(opts.min!=null){
            var f_min = parseFloat(opts.min);
            var f_num = parseFloat(num);
            var result = f_num-f_min;
            if(result < 0){
                var maxTipStr = opts.maxTipStr || "您输入的数字不能小于"+f_max+"!";
                layer.tips(maxTipStr,$input);
                return false;
            }
        }
        return true;
    };

    /**
     * 字数输入检查
     * @param $input 输入框对象
     * @param options 参数配置
     */
    exports.unInputNumFormat=function ($input,options) {
        layer.config({
            tipsMore:false
        });
        var defaults = {
            type:0,             //类型(小数位数，0为正整数)
            tipStr:null,        //提示语
            max: null,          //最大值
            maxTipStr:null,     //超过最大值提示语
            min:null,           //最小值
            tipMinStr:null      //少于最小值提示语
        };
        var opts = $.extend(defaults, options);
        $input.keyup(function(e){
            var keyCode = e.keyCode;
            if( (keyCode > 95 && keyCode < 106 )|| keyCode == 110 ||//小键盘
                (keyCode > 47 && keyCode < 58) || keyCode == 190 || keyCode == 8 || //键盘
                (keyCode > 34 &&keyCode < 41) //home end 上下左右
                || keyCode == 46 //退格键
            ) {
                //正数
                if(opts.type==0 && (keyCode == 110 || keyCode == 190)){
                    return false;
                }
            }else {
                return false;
            }
        }).blur(function(e){
            var $this = $(this);
            //最后一位是小数点的话，移除
            //$this.val(($this.val().replace(/\.$/g, "")));
            exports.checkNumFormatInput($this,opts);
        });
    };
    /**
     * 秒钟倒计时
     * @param {$} jqObj 显示秒数容器
     * @param {$} secs 为设定秒数
     * @param {function}  callback 为0秒时回调接入口
     * */
    exports.loadSecond = function(jqObj,secs,callback){
        var i=secs;
        var t= setInterval(function(){
            if(i == 0) {
                clearInterval(t);
                if(typeof(callback) == "function") callback();
            }else{
                //jqObj.text('请等待 ' + i + ' s');
                jqObj.text(i);
            }
            i--;
        },1000);
    };
    /**
     * 获取短信验证码
     * @param {$} $getBtn 按钮对象
     * @param {$} $mobile 手机号码文本框对象
     * @param {string}  getUrl 获取操作url
     * @param {boolean}  isGeetest 是否使用极验
     * @param {msgType}
     * case 1:break;//修改会员账号
     case 2:break;//修改登录密码,忘记密码
     case 3:break;//修改交易密码
     case 4:break;//注册大塑支付
     mpe注册不需要msgType
     * */
    exports.getCode = function($getBtn,msgType,$mobile,getUrl){

        //获取短信接口
        var getSMS = function(){
            //发送短信
            $.ajax({
                url: getUrl,
                type: 'post',
                async:false,
                data: {
                    mobile:$mobile==null ? null : $mobile.val(),
                    msgType:msgType
                },
                dataType: 'json',
                success: function(data){
                    if(data.code=='000'){
                        //确定已获取短信
                        $getBtn.off().removeClass("active").prop("disabled",true).html('重新获取（<i>120</i>）');
                        layer.open({type:1,title: false,closeBtn:0,content:"验证码已发出，请注意查收!<br/>如未收到，请重新获取",skin:"layui-layer-hui",success:function(l,i){
                            setTimeout(function(){
                                layer.close(i)
                            },3000);
                        }});
                        //倒计时
                        exports.loadSecond($getBtn.find('i'), 120, function(){
                            $getBtn.addClass("active").prop("disabled",false).html('重新获取短信').on('click', handleFn);
                            return false;
                        });
                    }else{
                        layer.alert("<p class='c-danger'>"+data.message+"</p>",{title:"温馨提示"});
                    }
                }
            });
        };
        var getUrl= getUrl || "/admin/fund/getSMS";
        //处理入口
        var handleFn=function(){
            var active=$getBtn.data("active");
            if(!active){
                return false;
            }
            layer.load();
            getSMS();
            layer.closeAll("loading");
            return false;
        };
        $getBtn.on('click', handleFn);
    };

    /**
     * 简单气泡说明
     * @example
     *      <span data-act="tooltipcol" data-text="test tip">tip</span>
     * */
    exports.tooltips=function(){
        //只一次初始化
        if($("#toolTip").length){
            return;
        }
        var html='<div class="tool-tip" id="toolTip" style="z-index: 99999999;">' +
            '<div class="tool-tip-recive">tooltips内容</div>' +
            '<i class="ar_up"></i><i class="ar_up_in"></i>' +
            '</div>';

        $("body").append(html);

        var $tooltipcol = $('[data-act="tooltipcol"]');
        var $toolTip = $(".tool-tip");//tip浮层
        var $toolTipRecive = $toolTip.find(".tool-tip-recive");

        $(document).on("mouseenter",'[data-act="tooltipcol"]',function(){
            var $this = $(this);
            var dataText = $this.data("text");
            $toolTipRecive.html(dataText);
            /*
             *当前图标添加hover
             * */
            if($this.hasClass("icon_tip")){
                $this.addClass("icon_tip_hover");
            }
            $tooltipcol["flag"] = $this;

            var $left = $this.offset().left;
            var $top = $this.offset().top;
            var $toolTipW = $toolTip.width()/2;
            var $toolTipH = $toolTip.height();
            //$this.width()/2本身元素宽度的一半
            //-16箭头的总宽度
            //$toolTip.css({left:($left-$toolTipW)-16+$this.width()/2,top:$top+$this.height()+8});
            $toolTip.css({left:($left-$toolTipW)-16+$this.width()/2,top:$top-$this.height()-$toolTipH-24});
            $toolTip.show();
        });
        $(document).on("mouseleave",'[data-act="tooltipcol"],.tool-tip',function(){
            $toolTip.hide();
            var $version_tooltip_css = $(".icon_tip");
            if($version_tooltip_css){
                $version_tooltip_css.removeClass("icon_tip_hover");
            }
        });
        $(document).on("mouseenter",".tool-tip",function(){
            $toolTip.show();
            var $version_tooltip_css = $(".icon_tip");
            if($version_tooltip_css){
                $tooltipcol["flag"].addClass("icon_tip_hover");
            }
        });
    };
});

/**
 * select有默认选中值处理
 *
 * */
if ($("select").size() > 0) {
    $("select").each(function () {
        var val = $(this).data("value");
        if(val=='0'){
            $(this).val(val);

        }else{
            if (!!val) {
                $(this).val(val);
            }
        }

    });
}

//全站消息提醒
var timeOutId = 0;
var load_time = parseInt(new Date().getTime() / 1000);    // 当前时间戳

function ajaxNewMessage(start_time) {


    $.get('/admin/message/getUnHandledMessage', {start_time: start_time}, function (data) {

        if (data.data.counts > 0) {

            $('.unhandle-message-counts-span').html('<span class="badge" >' + data.data.counts + '</span>');

        } else {

            $('.unhandle-message-counts-span').html('');

            return false;
        }
        var items = data.data.items;
        var len = items.length;
        var message_html = '';
        for (var i = 0; i < len; i++) {

            //alert(items[i].id);
            message_html += '<li style="padding: 5px 2px;border-bottom: 1px solid #eee;"><a href="/admin/message/index.shtml" style="word-wrap: break-word;white-space:normal">' + items[i].message_content + '</a></li>';

        }
        message_html += '<li style="padding: 5px 2px;border-bottom: 1px solid #eee;text-align: center"><a href="/admin/message/index.shtml" style="word-wrap: break-word;white-space:normal">查看全部</a></li>';

/*        $('.unhandle-message-ul').html(message_html);
        var realtitle = document.title.replace(/\(\s*\d+\s*条消息\)/, "");
        var thistitle = '( ' + data.data.counts + ' 条消息)' + realtitle;
        document.title = thistitle;*/
    }, 'json');

    var new_load_time = parseInt(new Date().getTime() / 1000);

    var interval_time = 360 * 1000//间隔时间360秒

    timeOutId = setTimeout("ajaxNewMessage(" + new_load_time + ")", interval_time);
}
ajaxNewMessage(load_time);

$("#J_Export_btn").click(function (e) {
    $(this).closest('form').append($('<input type="hidden" name="export" value="1" class="J_Export_Hidden_Input">'));
    $(this).closest('form').submit();
    $('.J_Export_Hidden_Input').val(0);
});

var selectSetValue = function($obj){
    var $chosen = $obj.find(".chosen");
    var val = $chosen.find("input").val();
    var $span = $chosen.find("span");
    if (val!=""){
        $obj.find("li").each(function(){
            if(val == $(this).data("value")){
                var html = $(this).html();
                $span.html(html);
            }
        });
    }

    if($span.html()!="") return ;
    var first = $obj.find("li").first();
    $chosen.find("input").val(first.data("value"));
    $span.html(first.html());
    return false;


};
if($(".css-select").length>0){
    $(".css-select").each(function(){
        selectSetValue($(this));
    });
    $(".css-select").on("click",".chosen",function(){
        $(this).parent().toggleClass("open");
        $(this).next("ul").slideToggle("fast");
        return false;
    });
    $(document).on("click.chosen",function(e){
        if (e && e.which === 3) return
        $.each($(".css-select"),function(){
           var $this = $(this);
            if($this.hasClass("open")){
                $this.next("ul").slideUp("fast");
                $this.removeClass("open").find("ul").slideUp();
            }
        });

    });
    $(".css-select").on("click","li",function(i,e){
        var $select = $(this).parents(".css-select");
        $select.find(".chosen input").val($(this).data("value"));
        $select.find(".chosen span").html($(this).html());
        $(this).parent("ul").hide();
        $select.toggleClass("open");
    });
}

// 换皮肤
$("#changeSkin").on("click","a",function(){
   var val = $(this).data("val");
    $.post("/admin/member/setSkin", {
        skin: val,
    }, function (data) {
        if (data.code == '000') {
            JDialog.tip.work({type: "ok", content: data.message, lock: false, timer: __global.jdialog.timer,callback:function(){
                location.reload(true);
            }});
        } else {
            JDialog.tip.work({
                type: "error",
                content: data.message,
                lock: false,
                timer: __global.jdialog.timer
            });
        }
    }, 'json');
});

//导航选中
if($("#leftNav").length>0) {
    var type = $("#leftNav").data("type");
    $("#topNav li").each(function(){
        var this_type = $(this).data("type");
        if(type==this_type) {
            $(this).children("a").addClass("active");
            return false;
        }
    });
}


// setInterval(function (e) {
//     $('#J_Export_Hidden_Input').val(0);
// }, 1000);


